const request = require("request")
const { JSDOM } = require("jsdom")
// const fs=require("fs")
const { recommendDetailTable } = require("./recommendDetailTable")

module.exports = {
    getRecommendDetailData(req, res) {

        recommendDetailTable.find({
            id: req.params.id
        }).then((data) => {
            if (data.length === 0) {
                request({
                    method: "GET",
                    url: `https://i.y.qq.com/n2/m/share/details/taoge.html`,
                    qs: {
                        ADTAG: "myqq",
                        from: "myqq",
                        id: req.params.id
                    },
                    // headers:{
                    //     "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
                    // }
                }, (err, response, data) => {
                    // console.log(Object.keys(req.body))
                    let dom = new JSDOM(data, { runScripts: "dangerously" })
                    let songlist = dom.window.firstPageData
                    console.log(songlist.taogeData)
                    console.log("当前数据库中无数据");
                    let finalData = {}; //存储待添加到数据库的数据
                    finalData.id = req.params.id;
                    finalData.cover = songlist.taogeData.picurl || songlist.taogeData.headurl; //设置封面
                    finalData.title = songlist.taogeData.title; //设置专辑标体
                    finalData.tag = []; //预设一个空的数据,存储专辑类型
                    finalData.songlist = []; //预设一个空的数据,存储专辑歌曲列表
                    songlist.taogeData.tag.forEach(item => {
                        finalData.tag.push({
                            id: item.id,
                            name: item.name
                        });
                    });
                    songlist.taogeData.songlist.forEach(item => {
                        let singer = [];
                        item.singer.forEach(singerList => {
                            singer.push(singerList);
                        });
                        finalData.songlist.push({
                            songMid: item.mid,
                            songName: item.name,
                            songAlbum: songlist.taogeData.title,
                            singer: singer
                        });
                    });
                    // recommendDetailTable.create(finalData)
                    res.send(JSON.stringify(finalData));
                })
            } else {
                // res.send(JSON.stringify(data));
            }
        })
    }
}